import {
	host,androidV,iosV
} from "@/static/js/config.js"
import promise from "./promise"
import store from '@/pages/store/index.js'
// import main from "@/utils/main.js"
// import methods from "@/utils/methods.js"

function addHost(url) {
	let currentHost = ''
	let hcHost = uni.getStorageSync('host')
	
	if(hcHost){
		 currentHost = hcHost
	}else{
		 currentHost = host
	}
	
	if (!/^(https|http)/.test(url)) {
		return currentHost + url
	}
	return url
};


//请求方法的封装，目前微信只支持post跟get访求，参数要求可以查看微信文档
let _loading = false
let ajaxTimes = 0;
export default {
	doGet(path, data = {}) {
		let url = addHost(path)
		return this.request('GET', url, data)
	},
	doPost(path, data = {}) {
		let url = addHost(path)
		return this.request('POST', url, data)
	},
	request(method, url, data) {
		let token = ''
		let hostStr = ''
		let hcHost = uni.getStorageSync('host')
		let hcToken = uni.getStorageSync('token')
		let v = ''
		let pkg = ''
		
		if(hcToken){
			token = hcToken
		}
		
		if(hcHost){
			hostStr = hcHost
		}else{
			hostStr = host
		}
		
		if(store.state.platform == 'android'){
			pkg = 'com.chs.braceletApp'
		}else{
			pkg = 'com.chs.braceletApp'
		}
		if(store.state.platform == 'android'){
			v = androidV
		}else{
			v = iosV
		}
		
		//console.log('hostStr:',hostStr)
		
		const  language = uni.getStorageSync('language') || 'zh-Hans';//获取缓存的语言设置
		let obj = {
			url,
			method,
			data,
			header: {
				info: token,
				url: hostStr,
				locale:language == 'zh-Hans' ? 'zh' : language,
				pkg:pkg,
				v:v,
				id:store.state.deviceId || '',
				os:store.state.platform || '',
				mod:store.state.deviceModel || '',
				app:2
				//'content-type': 'application/x-www-form-urlencoded'
			}
		}

		console.log("发送请求:", obj)
		ajaxTimes++;
		// 显示加载中 效果
		// uni.showLoading({
		// 	title: "加载中...",
		// 	mask: true,
		// });
		return new Promise((resolve, reject) => {
			uni.request({
				url: obj.url,
				method: obj.method,
				data: obj.data,
				header: obj.header,
				timeout: 60000,
				success: function(res) {
					//console.log("url:", url)
					console.log("收到数据:", res.data)
					// if (res.statusCode != 200) {
					// 	setTimeout(() => {
					// 		uni.showToast({
					// 			icon: 'none',
					// 			title: 'The server is busy, please try again later'
					// 		})
					// 	}, 500)
					// }
					if (res.data.code == 200 || res.data.code == 100 || res.data.code == 201) {
						resolve(res)
					} else {
						// console.log('问题')
						reject(res)
					}
				},
				fail: function(err) {
					reject('请求失败:', err)
				},
				complete: function(res) {
					ajaxTimes--;
					// if (ajaxTimes === 0) {
					// 	//  关闭正在等待的图标
					// 	setTimeout(() => {
					// 		uni.hideLoading();
					// 	}, 500)
					// }
				}
			})

		})
	},
}